package com.hujie.sqlqueryes.service.sql;

import com.hujie.sqlqueryes.dto.DslResultDTO;
import com.hujie.sqlqueryes.service.impl.QueryExpressionBuilderImpl;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.delete.Delete;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * DELETE语句处理器
 */
@Component
public class DeleteStatementHandler implements SqlStatementHandler {
    
    private static final Logger logger = LoggerFactory.getLogger(DeleteStatementHandler.class);
    
    @Autowired
    private QueryExpressionBuilderImpl queryExpressionBuilder;
    
    @Override
    public boolean supports(Statement statement) {
        return statement instanceof Delete;
    }
    
    @Override
    public DslResultDTO handle(Statement statement) {
        try {
            Delete deleteStatement = (Delete) statement;
            String dsl = buildDslFromDelete(deleteStatement);
            logger.info("DELETE语句转换完成");
            logger.debug("生成的DSL: {}", dsl);
            return DslResultDTO.success(dsl);
        } catch (Exception e) {
            logger.error("DELETE语句转换失败: {}", e.getMessage(), e);
            return DslResultDTO.error("DELETE语句转换失败: " + e.getMessage());
        }
    }
    
    private String buildDslFromDelete(Delete deleteStatement) {
        Table table = deleteStatement.getTable();
        String tableName = table.getName();
        
        // 处理包含特殊字符的索引名称（去除方括号）
        if (tableName != null && tableName.startsWith("[") && tableName.endsWith("]")) {
            tableName = tableName.substring(1, tableName.length() - 1);
        }
        
        // 获取WHERE条件
        Expression where = deleteStatement.getWhere();
        
        StringBuilder dsl = new StringBuilder();
        dsl.append("{\n");
        dsl.append("  \"operation\": \"delete\",\n");
        dsl.append("  \"index\": \"").append(tableName).append("\",\n");
        
        // 处理WHERE条件
        if (where != null) {
            dsl.append("  \"query\": ").append(queryExpressionBuilder.buildQueryFromExpression(where)).append("\n");
        } else {
            // 如果没有WHERE条件，表示删除所有文档（危险操作）
            dsl.append("  \"query\": {\n    \"match_all\": {}\n  }\n");
        }
        
        dsl.append("}");
        return dsl.toString();
    }
}